<template>
  <!-- 自定义表格 -->
  <custom-table
    ref="customTableRef"
    row-key="id"
    :columns="columns"
    :api="clueMessageListCRUD.page"
    column-controller-key="orderRecordList"
  >
    <template #topContent>
      <div style="margin-bottom: var(--td-comp-margin-s)">
        <t-button
          @click="
            handleOpenDialog('create', { tlClueId, messageType: 1, topStatus: 0, imageUrl:[] })
          "
        >
          新建回访
        </t-button>
      </div>
      <!-- 记录类型 -->
      <div style="margin-bottom: var(--td-comp-margin-s)">
        <t-radio-group v-model:value="selectedType" @change="handleInitTable">
          <t-radio-button
            v-for="_ in [{ label: '全部', value: '' }, ...dictionaryStore.get('decoration_order_record_type')]"
            :key="_.value"
            :value="_.value"
          >
            {{ _.label }}
          </t-radio-button>
        </t-radio-group>
      </div>
      <!-- 置顶记录 -->
      <t-alert
        v-if="topOrderRecord.message||topOrderRecord.creator||topOrderRecord.createTime"
        :title="topOrderRecord.message"
        :message="`${topOrderRecord.creatorName} ${dayjs(topOrderRecord.createTime).format('YYYY-MM-DD HH:mm:ss')}`"
      />
    </template>
    <template #imageUrl="{ row }">
      <image-viewer :images="(JSON.parse(row.imageUrl)).map((f: Record<string, string>) => f.url)" width="40px" height="40px" v-if="row.imageUrl" />
    </template>
    <template #messageType="{ row }">
      {{ dictionaryStore.analysis('decoration_order_record_type', row.messageType) }}
    </template>
    <template #createTime="{ row }">
      {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
    </template>
    <template #operation="{ row }">
      <t-space>
        <t-popconfirm content="确认要置顶该项吗？" @confirm="handleSetTop(row)">
          <t-link theme="primary"> 置顶 </t-link>
        </t-popconfirm>
      </t-space>
    </template>
  </custom-table>
  <!-- 自定义对话框 -->
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData, readonly }"
    :api-map="clueMessageListCRUD"
    header="*回访"
    @request-success="handleDialogRequestSuccess"
  >
    <t-form-item label="回访内容" name="message" :rules="[{ required: true, message: '请输入回访内容' }]">
      <mention
        v-model:value="formData.message"
        placeholder="请输入回访内容"
        :readonly="readonly"
      />
    </t-form-item>
    <t-form-item label="图片" name="imageUrl" >
      <upload 
        v-model:files="formData.imageUrl" 
        accept="image/*" 
        theme="image"
        multiple
      />
    </t-form-item>
    <t-form-item label="是否置顶" name="topStatus" :rules="[{ required: true, message: '请选择是否置顶' }]">
      <t-radio-group v-model:value="formData.topStatus">
        <t-radio
          v-for="_ in [
            { label: '是', value: 1 },
            { label: '否', value: 0 },
          ]"
          :key="_.value"
          :value="_.value"
          :readonly="readonly"
        >
          {{ _.label }}
        </t-radio>
      </t-radio-group>
    </t-form-item>
  </custom-dialog>
  <!-- 粘性审批对话框 -->
  <!-- <sticky-approve-dialog ref="stickyApproveDialogRef1" :order-id="tlClueId" approve-type="1" />
  <sticky-approve-dialog ref="stickyApproveDialogRef2" :order-id="tlClueId" approve-type="2" />
  <sticky-approve-dialog ref="stickyApproveDialogRef3" :order-id="tlClueId" approve-type="3" />
  <sticky-approve-dialog ref="stickyApproveDialogRef4" :order-id="tlClueId" approve-type="4" />
  <sticky-approve-dialog ref="stickyApproveDialogRef25" :order-id="tlClueId" approve-type="25" />
  <sticky-approve-dialog ref="stickyApproveDialogRef27" :order-id="tlClueId" approve-type="27" /> -->
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { inject, onMounted, Ref, ref, useTemplateRef } from 'vue';


import { clueMessageListCRUD } from '@/api/delivery/clue';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import Mention from '@/components/mention/index.vue';
import Upload from '@/components/upload/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import StickyApproveDialog from '@/pages/approve/components/sticky-approve-dialog .vue';
import { useDictionaryStore, useUserStore } from '@/store';

// 定义 props
const props = defineProps({
  injectKey: {
    type: String,
    default: 'clueDetails',
  },
});
// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 默认的注入键
const injectKey = props.injectKey
// 动态注入数据
const details = inject<Ref<Record<string, any>>>(injectKey);
// 将原有的 clueDetails 替换为 details
const clueDetails = details;
console.log(clueDetails.value);

const tlClueId = details.value.tlClueId || details.value.id

// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'creatorName', title: '跟进人', width: 150 },
  { colKey: 'message', title: '跟进内容' },
  { colKey: 'imageUrl', title: '图片' },
  { colKey: 'messageType', title: '记录类型', width: 100 },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 60, fixed: 'right' },
];
// 选择的类型
const selectedType = ref('');
// 置顶订单记录
const topOrderRecord = ref<Record<string, any>>({});
// 处理获取置顶订单记录
const handleGetTopOrderRecord = () => {
  const params = {
    tlClueId,
    topStatus: '1',
  };
  clueMessageListCRUD
    .page(params)
    .then((data) => {
      topOrderRecord.value = data.list[0] || {};
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理初始化表格
const handleInitTable = () => {
  handleGetTopOrderRecord();
  const params = { tlClueId, messageType: selectedType.value };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  handleGetTopOrderRecord();
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  // handleGetOrderRelevantPerson();
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理置顶
const handleSetTop = (row: Record<string, any>) => {
  const params = {
    ...row,
    topStatus: 1,
  };
  clueMessageListCRUD
    .update(params)
    .then(() => {
      MessagePlugin.success('置顶成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 粘性审批对话框ref
// const stickyApproveDialogRef1 = useTemplateRef('stickyApproveDialogRef1');
// const stickyApproveDialogRef2 = useTemplateRef('stickyApproveDialogRef2');
// const stickyApproveDialogRef3 = useTemplateRef('stickyApproveDialogRef3');
// const stickyApproveDialogRef4 = useTemplateRef('stickyApproveDialogRef4');
// const stickyApproveDialogRef25 = useTemplateRef('stickyApproveDialogRef25');
// const stickyApproveDialogRef27 = useTemplateRef('stickyApproveDialogRef27');
onMounted(() => {
  const { approveType } = clueDetails.value;
  // if (approveType === '1') stickyApproveDialogRef1.value.open();
  // if (approveType === '2') stickyApproveDialogRef2.value.open();
  // if (approveType === '3') stickyApproveDialogRef3.value.open();
  // if (approveType === '4') stickyApproveDialogRef4.value.open();
  // if (approveType === '25') stickyApproveDialogRef25.value.open();
  // if (approveType === '27') stickyApproveDialogRef27.value.open();
});
</script>
